import amqp, { Message } from 'amqplib';
interface EmailTask {
    to: string;
    subject: string;
    body: string;
}

// 处理消息失败，判断是否需要进行重试
const maxRetryAttempts = 3; // 最大重试次数

async function consumeEmailTasks() {
    const connection = await amqp.connect('amqp://mingcai_mq:EUDNfpZRbhfjb8PZ@95.169.25.181');
    const channel = await connection.createChannel();
    const queueName = 'email_tasks';

    // 声明一个持久化的邮件任务队列
    await channel.assertQueue(queueName, { durable: true });

    console.log('Waiting for mail tasks to be processed...');

    // 处理邮件任务消息
    await channel.consume(queueName, async (msg: Message | null) => {
         if (msg) {

             const data: EmailTask = JSON.parse(msg.content.toString());
             let retryCount = msg.properties.headers['x-retry-count'] || 0;
             const messageId = msg.properties.messageId


             console.log('Processing message:', data);
             console.log(`[x] ${messageId} Retry count:`, retryCount);
             try {
                 if (data.to.includes("recipient1@sse.com")) {
                     throw new Error(`email to ${data.to}  send fail...`);
                 }
                 //发送邮件
                 await new Promise(resolve => setTimeout(resolve, 1000));
                 channel.ack(msg);
             } catch (error) {
                 console.error(`error:${error}`);
                 // 增加重试次数
                 retryCount++
                 // 判断是否达到最大重试次数
                 if (retryCount < maxRetryAttempts) {
                     // 重新发送消息到队列
                     channel.sendToQueue(queueName, msg.content,  {
                         headers: {
                             'x-retry-count': retryCount
                         }
                     });
                     console.log(' [x] Rejected and requeued with updated retry count:', retryCount);

                 } else {
                     // 不进行重试，将消息从队列中移除
                     channel.ack(msg);
                 }
             }

         }
    });


    // 关闭连接
    process.on('SIGINT', () => {
        console.log('消费者中断，关闭连接...');
        connection.close();
    });
}

// 调用消费函数
consumeEmailTasks();
